package com.zjitc.book.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import com.zjitc.book.Dto.UserDto;

import com.zjitc.book.common.result.R;
import com.zjitc.book.entity.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


//@CrossOrigin
@RestController
@RequestMapping("/api")
public class UserController {

    private static final String key = "12345678912345678912345";

    @Autowired
    AuthenticationManager authManager;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/auth/login")
    public R<Map<String,Object>> login(@RequestBody UserDto user){
        System.out.println(user);
        //1.借助authManager来完成认证
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authManager.authenticate(auth);

        //2.从authenticate中获取用户信息
        MyUserDetails userDetails = (MyUserDetails) authenticate.getPrincipal();
        Integer userid = userDetails.getUser().getId();
        String username = userDetails.getUser().getUsername();
        List<String> authorities = userDetails.getAuthors();

        //2.1 把登录的用户权限存入redis
        stringRedisTemplate.opsForSet().add("user:perms:"+userid,authorities.toArray(new String[0]));



        //3.用hutool工具去生成JWT令牌（token）
        Map<String,Object> map = new HashMap();
        map.put("userid",userid);
        map.put("username",username);
        map.put("exp", DateUtil.currentSeconds()+60*60);
        String token = JWTUtil.createToken(map, key.getBytes());

        //4.响应
        HashMap<String, Object> res = new HashMap<>();
        res.put("token",token);
        res.put("userid",userid);
        res.put("username",username);
        return R.success(res);
    }
}





